<?php

/**
 * 用户特殊权限操作基类
 */
namespace Home\Controller;

class AccessUserController extends BaseUserController {
	/**
	*前台需要验证权限的操作
	*/
	protected $authRule = array();

	protected function _initialize(){
		parent::_initialize();
		$this->authRule = C('HOME_AUTH_RULE');
		#TODO 判断当前操作权限
		/*$rule = CONTROLLER_NAME.'/'.ACTION_NAME;
		if($this->accessControl($rule)){
			$check = $this->checkRule($rule);
			if(!$check)
				$this->error('非法操作');
		}*/
	}

	/**
	*检测用户操作权限
	*/
	public function check($rule){

		if($this->accessControl($rule)){
			$check = $this->checkRule($rule);
			if(!$check)
				return false;
		}

		return true;
	}

	/**
	*检测当前操作是否是特殊操作
	*@param string $action 检测的操作
	*@return boolean true:直接访问，false:需要检测用户操作权限 
	*/
	public function accessControl($action=''){

		if($action && in_array_case($action, $this->authRule))
			return true;
		else
			return false;
	}

	/**
	*检测用户是否有操作权限
	*@param string $action 操作名 CONTROLLER/ACTION
	*@return boolean true:合法访问， false:非法操作
	*/
	public function checkRule($action){

		$userRule = $this->getRuleList();
		if(empty($userRule))
			return false;

		$actionKey = $this->getActionKey($action);
		if(in_array($actionKey, $userRule))
			return true;
		else
			return false;
	}

	/**
	*根据action，获取其设置的相应的权限值
	*@param string $action 操作
	*@return 
	*/
	private function getActionKey($action){
		$action = strtolower($action);
		foreach ($this->authRule as $key => $value) {
			if($action === strtolower($value))
				return $key;
		}
	}

	/**
	*获取用户的所有需要验证的操作权限
	*@return array
	*/
	private function getRuleList(){
		static $_hAuthList = array();
		if (isset($_hAuthList[UID])) {
            return $_hAuthList[UID];
        }

		$filter = array('a.uid'=>UID, 'g.status'=>1, 'g.type'=>2,);
		$userGrp = M('auth_group_access a')->join('__AUTH_GROUP__ g on a.group_id=g.id')
					->where($filter)->field('a.uid,g.rules')->select();

		$ids = array();//保存用户所属用户组设置的所有权限规则标识
        foreach ($userGrp as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        if (empty($ids)) {
            $_hAuthList[UID] = array();
            return array();
        }
        $_hAuthList[UID] = $ids;
        return $ids;
	}

}